package com.smugmugsoftware.airconcalc.advanced;

import java.util.Iterator;
import java.util.Vector;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class AdvancedRoomListFragment extends Fragment implements RoomListFragmentInterface {

	private SharedPreferences prefs;
	private MainActivityInterface activity;
	private Building thisBuilding;

	private View thisView;
	private ListView roomList;
	private boolean useTons;
	private Thread redrawThread;

	public AdvancedRoomListFragment() {}

	public AdvancedRoomListFragment(Building building) {
		thisBuilding = building;
		thisBuilding.attachChildren();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		prefs = getActivity().getSharedPreferences("config.dat", Context.MODE_PRIVATE);
		useTons = prefs.getBoolean("USE_TONS", false);

		setRetainInstance(true);

		if (savedInstanceState != null && savedInstanceState.getParcelable("SAVED_BUILDING") != null) {
			thisBuilding = savedInstanceState.getParcelable("SAVED_BUILDING");
			thisBuilding.attachChildren();
		}

		prefs = getActivity().getSharedPreferences("config.dat", Context.MODE_PRIVATE);

	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			this.activity = (MainActivityInterface) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString() + " must implement OnHeadlineSelectedListener");
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		thisView = inflater.inflate(R.layout.advanced_room_list_fragment, container, false);
		roomList = (ListView) thisView.findViewById(R.id.room_list);
		final RoomListAdapter<Room> roomListAdapter = new RoomListAdapter<Room>(thisView.getContext(), thisBuilding.getRooms());
		roomList.setAdapter(roomListAdapter);

		ImageView addButton = (ImageView) thisView.findViewById(R.id.new_room_button);
		addButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				activity.openRoomEditor(1000, thisBuilding);
			}
		});

		ImageView globalButton = (ImageView) thisView.findViewById(R.id.change_global_button);
		globalButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				activity.openLocaleEditor(thisBuilding);
			}
		});

		ImageView reportButton = (ImageView) thisView.findViewById(R.id.report_button);
		reportButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				activity.openReport(thisBuilding);
			}
		});

		ImageView chartButton = (ImageView) thisView.findViewById(R.id.chart_button);
		chartButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				activity.openChart(thisBuilding);
			}
		});

		roomList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				activity.openRoomEditor(id, thisBuilding);
			}
		});

		roomList.setOnItemLongClickListener(new OnItemLongClickListener() {

			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

				activity.displayConfirmDialog(thisView.getContext(), ConfirmDialog.DELETE, ROOM_LIST, id);
				return false;
			}
		});

		if (thisView.findViewById(R.id.localeLabelWrapper) != null) {
			TextView installer = (TextView) thisView.findViewById(R.id.installer);
			TextView address = (TextView) thisView.findViewById(R.id.address);
			TextView locale = (TextView) thisView.findViewById(R.id.locale);
			TextView latitude = (TextView) thisView.findViewById(R.id.latitude);
			TextView latitudeNS = (TextView) thisView.findViewById(R.id.latitude_unit_label);
			TextView designTemp = (TextView) thisView.findViewById(R.id.internal);
			TextView externalTemp = (TextView) thisView.findViewById(R.id.external);
			TextView dailyRange = (TextView) thisView.findViewById(R.id.daily_range);
			TextView constTightness = (TextView) thisView.findViewById(R.id.tightness);

			if (thisBuilding.getEstimatorName().length() > 16 && thisBuilding.getEstimatorName().length() <= 26) {
				installer.setTextSize(12);
				installer.setText(thisBuilding.getEstimatorName());
			} else if (thisBuilding.getEstimatorName().length() > 26) {
				installer.setTextSize(12);
				installer.setText(thisBuilding.getEstimatorName().substring(0, 23) + "...");
			} else {
				installer.setTextSize(14);
				installer.setText(thisBuilding.getEstimatorName());
			}

			if (thisBuilding.getAddress().length() > 20 && thisBuilding.getAddress().length() <= 30) {
				address.setTextSize(12);
				address.setText(thisBuilding.getAddress());
			} else if (thisBuilding.getAddress().length() > 30) {
				address.setTextSize(12);
				address.setText(thisBuilding.getAddress().substring(0, 26) + "...");
			} else {
				address.setTextSize(14);
				address.setText(thisBuilding.getAddress());
			}

			locale.setText(thisBuilding.getLocaleName());
			designTemp.setText(String.valueOf(thisBuilding.getInternalTemp()));
			externalTemp.setText(String.valueOf(thisBuilding.getExternalDryBulb()));
			dailyRange.setText(String.valueOf(thisBuilding.getDailyRangeInt()));
			constTightness.setText(thisBuilding.getConstrutionTightnessString());

			int thisLatitude = thisBuilding.getActualLatitude();
			if (thisLatitude <= 0) {
				thisLatitude = thisLatitude * -1;
				latitudeNS.setText("S");
			} else {
				latitudeNS.setText("N");
			}

			latitude.setText(String.valueOf(thisLatitude));
		}

		if (thisView.findViewById(R.id.footerWrapper) != null) {
			ImageView switchButton = (ImageView) thisView.findViewById(R.id.switch_button);
			switchButton.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					if (useTons) {
						prefs.edit().putBoolean("USE_TONS", false);
						useTons = false;
					} else if (!useTons) {
						prefs.edit().putBoolean("USE_TONS", true);
						useTons = true;						
					}

					redrawTotals();
				}
			});
		}

		return thisView;
	}

	@Override
	public void onResume() {
		super.onResume();

		new Thread(new Runnable() {	
			public void run() {
				TextView infiltrationCFM = (TextView) thisView.findViewById(R.id.infiltration_cfm);
				TextView infiltrationBTU = (TextView) thisView.findViewById(R.id.infiltration_btu);

				setViewText(infiltrationCFM, String.valueOf((int) thisBuilding.getInfiltrationCFM()));
				setViewText(infiltrationBTU, String.valueOf((int) thisBuilding.getInfiltrationBTU()));

				Room thisRoom = null;
				Iterator<Room> iterator = thisBuilding.getRooms().iterator();
				while (iterator.hasNext()) {
					thisRoom = iterator.next();
					thisRoom.setBTUString(String.valueOf((int) thisRoom.getTotalRoomLoad(thisView.getContext())));

					if (getActivity() != null) {
						getActivity().runOnUiThread(new Runnable() {

							public void run() {
								((RoomListAdapter<Room>) roomList.getAdapter()).notifyDataSetChanged();
							}
						});
					}
				}
			}
		}).start();

		redrawTotals();
	}

	private void redrawTotals() {

		final TextView total = (TextView) thisView.findViewById(R.id.total);
		final TextView totalLabel = (TextView) thisView.findViewById(R.id.total_units);

		redrawThread = new Thread(new Runnable() {

			public void run() {

				setViewText(total, "CALCULATING");
				setViewText(totalLabel, "");

				double totalLoad = thisBuilding.getTotalBuildingLoad(thisView.getContext());
				totalLoad = totalLoad + thisBuilding.getInfiltrationBTU();

				if (!useTons) {
					setViewText(total, String.valueOf((int) thisBuilding.getTotalBuildingLoad(thisView.getContext())));
					setViewText(totalLabel, "BTU");
				} else if (useTons) {
					String tonsString = String.valueOf(thisBuilding.getBuildingLoadInTons(thisView.getContext()));
					double tons = activity.getDecimalFromString(tonsString);
					tonsString = activity.getNumberString(tons, 2);
					setViewText(total, tonsString);
					setViewText(totalLabel, "Tons");
				}
			}
		});
		redrawThread.start();

	}


	protected void setViewText(final TextView v, final String s) {
		if (getActivity() != null) {
			getActivity().runOnUiThread(new Runnable() {

				public void run() {
					v.setText(s);
				}
			});
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		outState.putParcelable("SAVED_BUILDING", thisBuilding);
	}

	public void returnFromConfirmDialog(int dialogType, int type, long id) {
		if (dialogType == ConfirmDialog.DELETE) {
			thisBuilding.removeRoom(id);
			((RoomListAdapter<Room>) roomList.getAdapter()).notifyDataSetChanged();
			redrawTotals();
		}
	}
}